package net.thxjj.adminServer.controller;

import com.alibaba.fastjson.JSONObject;
import net.thxjj.adminServer.controller.base.BaseController;
import net.thxjj.adminServer.entity.*;
import net.thxjj.adminServer.entity.aep.EventBean;
import net.thxjj.adminServer.entity.aep.LoginData;
import net.thxjj.adminServer.entity.aep.ProfileLog;
import net.thxjj.adminServer.entity.aep.profilegc.ProfileGCInfoBean;
import net.thxjj.adminServer.entity.onenet.DataBean;
import net.thxjj.adminServer.entity.onenet.ModuleBean;
import net.thxjj.adminServer.entity.onenet.OnenetTransResultBean;
import net.thxjj.adminServer.entity.onenet.OnetEvent;
import net.thxjj.adminServer.service.*;
import net.thxjj.adminServer.util.DataUtils;
import net.thxjj.adminServer.util.ParameterMap;
import net.thxjj.adminServer.util.Tools;
import net.thxjj.sitermodel.Device;
import net.thxjj.sitermodel.User;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api")
public class UserApiController extends BaseController {

    private Logger log = Logger.getLogger(this.getClass());
    private final static String color_alert = "rgba(255, 0, 0, 1)";
    private final static String color_fault = "rgba(230, 162, 60, 1)";
    private final static String color_normal = "rgba(103, 194, 58, 1)";
    private final static String color_dismantle = "rgba(158, 158, 158, 1)";
    private final static String color_low_battery = "rgba(255, 235, 59, 1)";
    private final static String color_theme = "#409eff";

    @Autowired
    private IUserApiService iUserApiService;

    @Autowired
    private IDeviceService iDeviceService;

    @Autowired
    private IDevLogService iDevLogService;

    @Autowired
    private IDevHistoryService iDevHistoryService;

    @Autowired
    private IDeviceJsonService iDeviceJsonService;

    @Autowired
    private IDevHistoryDeepService iDevHistoryDeepService;

    @Autowired
    private IMainSurveyService iMainSurveyService;

    @Autowired
    private IDevOneNetLogService iDevOneNetLogService;

    @Autowired
    private IProfileLogService iProfileLogService;

    @Autowired
    private IExcelDeviceService iExcelDeviceService;

    @Autowired
    private IProfileGCService iProfileGCService;

    /**
     * 获取设备列表（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/getDevices",method= RequestMethod.GET)
    @ResponseBody
    public Object Devices(){

        //imei:关键字
        String imei = this.getParameterMap().getString("imei");
        //platform:即为prod_key
        String platform = this.getParameterMap().getString("platform");

        List<Long> deviceStatusFilter = new ArrayList<>();
        String deviceStatus = this.getParameterMap().getString("deviceStatus");
        if(!Tools.isEmpty(deviceStatus)){
            try {
                String[] dsa = deviceStatus.split(",");
                for (String item:dsa){
                    deviceStatusFilter.add(Long.parseLong(item));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }



        List<Long> netStatusFilter = new ArrayList<>();
        String netStatus = this.getParameterMap().getString("netStatus");
        if(!Tools.isEmpty(netStatus)){
            try {
                String[] dsa = netStatus.split(",");
                for (String item:dsa){
                    netStatusFilter.add(Long.parseLong(item));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }





       List<Device> list = iDeviceService.getDeviceList(imei,platform,deviceStatusFilter,netStatusFilter);

        return ResponseModel.getModel(ResultEnum.SUCCESS, list);

    }


    /**
     * 管理账号登录（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/login",method= RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object vLogin(@RequestBody JSONObject jsonParam){

        String username = jsonParam.getString("username");
        String password = jsonParam.getString("password");
        return iUserApiService.Login(username,password);
    }


    /**
     * 查询单个设备最新状态（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/queryDeviceStatus",method= RequestMethod.GET)
    @ResponseBody
    public Object queryDeviceStatus(){


        String deviceId = this.getParameterMap().getString("deviceId");

        if(StringUtils.isEmpty(deviceId)) return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        Device deviceBean = iDeviceService.getDeviceInfo(deviceId);
        if(deviceBean==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }

        ArrayList<ParameterMap> list = new ArrayList<>();
        if(Const.ONENET_PRODUCT_ID.equals(deviceBean.getProdKey())){
            OnetEvent onetEvent = iDevOneNetLogService.getSmokeStatus(deviceBean.getDeviceId());
            if(onetEvent!=null){
                OnenetTransResultBean onenetTransResultBean = onetEvent.transToBean(onetEvent.getEventContent());
                DataBean dataBean = onenetTransResultBean.getDataBean();
                if(dataBean!=null){
                    ParameterMap onetStatusMap = new ParameterMap();
                    onetStatusMap.put("datasetId","onenetstatus");
                    onetStatusMap.put("timestamp",onetEvent.getCreateTime());

                    ParameterMap smokeValueMap = new ParameterMap();
                    smokeValueMap.put("datasetId","smoke_value");
                    smokeValueMap.put("timestamp",onetEvent.getCreateTime());

                    ParameterMap batteryValueMap = new ParameterMap();
                    batteryValueMap.put("datasetId","battery_value");
                    batteryValueMap.put("timestamp",onetEvent.getCreateTime());
                    onetStatusMap.put("value",dataBean.getDevice_status());
                    smokeValueMap.put("value",dataBean.getSmoke_value());
                    batteryValueMap.put("value",dataBean.getBattery_value());
                    list.add(onetStatusMap);
                    list.add(smokeValueMap);
                    list.add(batteryValueMap);
                }
            }

            OnetEvent onetLoginEvent = iDevOneNetLogService.getSmokeLoginEvent(deviceBean.getDeviceId());
            if(onetLoginEvent!=null){
                OnenetTransResultBean onenetTransResultBean = onetLoginEvent.transToBean(onetLoginEvent.getEventContent());
                ModuleBean moduleBean = onenetTransResultBean.getModuleBean();
                if(moduleBean!=null){
                    ParameterMap softwareMap = new ParameterMap();
                    softwareMap.put("datasetId","software_version");
                    softwareMap.put("timestamp",onetEvent.getCreateTime());

                    ParameterMap hardwareMap = new ParameterMap();
                    hardwareMap.put("datasetId","hardware_version");
                    hardwareMap.put("timestamp",onetEvent.getCreateTime());


                    softwareMap.put("value",moduleBean.getSoftware_version());
                    hardwareMap.put("value",moduleBean.getModule_version());

                    list.add(softwareMap);
                    list.add(hardwareMap);

                }
            }

            ParameterMap multlogin = iDevOneNetLogService.isMultiLoginError(deviceId);
            ParameterMap heart = iDevOneNetLogService.HeartBeat(deviceId);
            list.add(multlogin);
            list.add(heart);
        }else if(Const.PROFILE_PRODUCT_ID.equals(deviceBean.getProdKey())){
            ProfileLog profileLog = iProfileLogService.ShadowStatus(deviceBean.getDeviceId());
            if(profileLog!=null){
                    ParameterMap onetStatusMap = new ParameterMap();
                    onetStatusMap.put("datasetId","profilestatus");
                    onetStatusMap.put("timestamp",profileLog.getTimestamp());

                    ParameterMap smokeValueMap = new ParameterMap();
                    smokeValueMap.put("datasetId","smoke_value");
                    smokeValueMap.put("timestamp",profileLog.getTimestamp());

                    ParameterMap batteryValueMap = new ParameterMap();
                    batteryValueMap.put("datasetId","battery_value");
                    batteryValueMap.put("timestamp",profileLog.getTimestamp());
                    onetStatusMap.put("value",profileLog.getAlarm_Status());
                    smokeValueMap.put("value",profileLog.getAlarmLevel());
                    batteryValueMap.put("value",profileLog.getBattery_Level());
                    list.add(onetStatusMap);
                    list.add(smokeValueMap);
                    list.add(batteryValueMap);
            }

            LoginData profileLoginData = iProfileLogService.ShadowLoginStatus(deviceBean.getDeviceId());
            if(profileLoginData!=null){
                    ParameterMap softwareMap = new ParameterMap();
                    softwareMap.put("datasetId","software_version");
                    softwareMap.put("timestamp",profileLoginData.getTimestamp());

                    ParameterMap hardwareMap = new ParameterMap();
                    hardwareMap.put("datasetId","hardware_version");
                    hardwareMap.put("timestamp",profileLoginData.getTimestamp());


                    softwareMap.put("value",profileLoginData.getSoftware_version());
                    hardwareMap.put("value",profileLoginData.getHardware_version());

                    list.add(softwareMap);
                    list.add(hardwareMap);

            }

            ParameterMap multlogin = iProfileLogService.isMultiLoginError(deviceId);
            ParameterMap heart = iProfileLogService.HeartBeat(deviceId);
            list.add(multlogin);
            list.add(heart);
        }else{
            ParameterMap sensorFaultStatus = iDevLogService.SensorFault(deviceId);
            ParameterMap smokeStatus = iDevLogService.SmokeAlarmStatus(deviceId);
            ParameterMap DismantleStatus = iDevLogService.DismantleStatus(deviceId);
            ParameterMap lowVoltFaultStatus = iDevLogService.LowVoltFault(deviceId);
            ParameterMap smokeValue = iDevLogService.SmokeValue(deviceId);
            ParameterMap batteryValue = iDevLogService.BatteryValue(deviceId);
            ParameterMap software = iDevLogService.SoftWareVersion(deviceId);
            ParameterMap hardware = iDevLogService.HardWareVersion(deviceId);
            ParameterMap multlogin = iDevLogService.isMultiLoginError(deviceId);
            ParameterMap heart = iDevLogService.HeartBeat(deviceId);
            list.add(smokeStatus);
            list.add(sensorFaultStatus);
            list.add(DismantleStatus);
            list.add(lowVoltFaultStatus);
            list.add(smokeValue);
            list.add(batteryValue);
            list.add(software);
            list.add(hardware);
            list.add(multlogin);
            list.add(heart);
        }

        ParameterMap parameterMap = new ParameterMap();
        parameterMap.put("deviceStatusList",list);
        parameterMap.put("device_name",deviceBean.getDeviceName());
        parameterMap.put("netStatus",deviceBean.getNetStatus());
        parameterMap.put("platform",deviceBean.getPlatform());
        parameterMap.put("productKey",deviceBean.getProdKey());
        long day = deviceBean.getHeartTime()/1440;
        long hour = deviceBean.getHeartTime()%1440/60;
        long min = deviceBean.getHeartTime()%1440%60;
        parameterMap.put("heart_time_day",day);
        parameterMap.put("heart_time_hour",hour);
        parameterMap.put("heart_time_min",min);
        return ResponseModel.getModel(ResultEnum.SUCCESS, parameterMap);
    }

    /**
     * 查询设备最近30天的数据记录
     * @return
     */
    @RequestMapping(value="/queryDeviceStatusHistory",method= RequestMethod.GET)
    @ResponseBody
    public Object queryDeviceStatusHistory(){

        String deviceId = this.getParameterMap().getString("deviceId");

        if(StringUtils.isEmpty(deviceId)) return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);

        Device deviceBean = iDeviceService.getDeviceInfo(deviceId);
        if(deviceBean==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }

        Calendar now = Calendar.getInstance();
        long curtime = now.getTime().getTime();
        now.add(Calendar.DAY_OF_MONTH, -30);
        long histime = now.getTime().getTime();
        List<List<Object>> list_smoke_state = new ArrayList<>();
        List<List<ParameterMap>> list_smoke = new ArrayList<>();
        if(Const.PROFILE_PRODUCT_ID.equals(deviceBean.getProdKey())){
            List<ProfileLog> list = iProfileLogService.getSmokeStatusList(deviceId,histime,curtime);
            for(int i=0;i<list.size();i++){

                    ProfileLog profileLog = list.get(i);
                    long status = profileLog.getAlarm_Status();
                    List<Object> listt = new ArrayList<>();
                    listt.add(profileLog.getTimestamp());
                    listt.add(status);
                    list_smoke_state.add(listt);
            }
        }else if(Const.ONENET_PRODUCT_ID.equals(deviceBean.getProdKey())){
           long startime = histime;
           OnetEvent event =  iDevOneNetLogService.getSmokeNewestStatus(deviceId,histime);
           if(event!=null){
               startime = event.getCreateTime();
           }
            List<OnetEvent> list = iDevOneNetLogService.getSmokeStatusList(deviceId,startime,curtime);
                for(int i=0;i<list.size();i++){
                    OnetEvent event1 = list.get(i);
                    OnenetTransResultBean onenetTransResultBean = event1.transToBean(event1.getEventContent());
                    if(onenetTransResultBean.getEventType()==1){
                       long status = onenetTransResultBean.getDataBean().getDevice_status();
                        List<Object> listt = new ArrayList<>();
                        listt.add(event1.getCreateTime());
                        listt.add(status);
                        list_smoke_state.add(listt);
                    }
                }
        }else{
            List<ParameterMap> listsmoke =  iDevHistoryService.smokeHappenList(deviceId,histime,curtime);

            List<ParameterMap> listfault =  iDevHistoryService.faultHappenList(deviceId,histime,curtime,1);

            List<ParameterMap> listlowvolt =  iDevHistoryService.faultHappenList(deviceId,histime,curtime,2);

            List<ParameterMap> listdismantle =  iDevHistoryService.faultHappenList(deviceId,histime,curtime,3);
            List<EventBean> list = new ArrayList<EventBean>();
            for (int i=0;i<listsmoke.size();i++){
                ParameterMap parameterMap = listsmoke.get(i);
                EventBean eventBean1 = new EventBean();
                eventBean1.setScore(100);
                eventBean1.setTimestamp(Long.parseLong(parameterMap.getString("start_time")));
                long a = Long.parseLong(parameterMap.getString("end_time"));
                EventBean eventBean2 = new EventBean();
                if (a == -1){
                    eventBean2.setScore(0);
                    eventBean2.setTimestamp(curtime);
                }else {
                    eventBean2.setScore(-100);
                    eventBean2.setTimestamp(a);
                }

                list.add(eventBean1);
                list.add(eventBean2);
            }

            for (int i=0;i<listfault.size();i++){
                ParameterMap parameterMap = listfault.get(i);
                EventBean eventBean1 = new EventBean();
                eventBean1.setScore(1000);
                eventBean1.setTimestamp(Long.parseLong(parameterMap.getString("start_time")));
                long a = Long.parseLong(parameterMap.getString("end_time"));
                EventBean eventBean2 = new EventBean();
                if (a == -1){
                    eventBean2.setScore(0);
                    eventBean2.setTimestamp(curtime);
                }else {
                    eventBean2.setScore(-1000);
                    eventBean2.setTimestamp(a);
                }
                list.add(eventBean1);
                list.add(eventBean2);
            }

            for (int i=0;i<listlowvolt.size();i++){
                ParameterMap parameterMap = listlowvolt.get(i);
                EventBean eventBean1 = new EventBean();
                eventBean1.setScore(1);
                eventBean1.setTimestamp(Long.parseLong(parameterMap.getString("start_time")));
                long a = Long.parseLong(parameterMap.getString("end_time"));
                EventBean eventBean2 = new EventBean();
                if (a == -1){
                    eventBean2.setScore(0);
                    eventBean2.setTimestamp(curtime);
                }else {
                    eventBean2.setScore(-1);
                    eventBean2.setTimestamp(a);
                }
                list.add(eventBean1);
                list.add(eventBean2);
            }

            for (int i=0;i<listdismantle.size();i++){
                ParameterMap parameterMap = listdismantle.get(i);
                EventBean eventBean1 = new EventBean();
                eventBean1.setScore(10);
                eventBean1.setTimestamp(Long.parseLong(parameterMap.getString("start_time")));
                long a = Long.parseLong(parameterMap.getString("end_time"));
                EventBean eventBean2 = new EventBean();
                if (a == -1){
                    eventBean2.setScore(0);
                    eventBean2.setTimestamp(curtime);
                }else {
                    eventBean2.setScore(-10);
                    eventBean2.setTimestamp(a);
                }
                list.add(eventBean1);
                list.add(eventBean2);
            }

            //根据时间线排序
            sortList(list);
            if(list.size()==0){
                List<ParameterMap> list1 = new ArrayList<>();
                ParameterMap start = new ParameterMap();
                ParameterMap end = new ParameterMap();
                ParameterMap ds = new ParameterMap();
                ds.put("color",color_normal);
                start.put("xAxis",histime);
                start.put("itemStyle",ds);
                end.put("xAxis",curtime);
                end.put("itemStyle",ds);
                list1.add(start);
                list1.add(end);
                list_smoke.add(list1);

                List<Object> lista = new ArrayList<>();
                lista.add(histime);
                lista.add(0);

                List<Object> listb = new ArrayList<>();
                listb.add(curtime);
                listb.add(0);

                list_smoke_state.add(lista);
                list_smoke_state.add(listb);

            } else{

                EventBean da = list.get(0);
                if(da.getTimestamp()>histime){
                    List<Object> listt = new ArrayList<>();
                    listt.add(histime);
                    listt.add(0);
                    list_smoke_state.add(listt);

                    List<ParameterMap> list1 = new ArrayList<>();
                    ParameterMap start = new ParameterMap();
                    ParameterMap end = new ParameterMap();
                    ParameterMap ds = new ParameterMap();
                    ds.put("color",color_normal);

                    start.put("xAxis",histime);
                    start.put("itemStyle",ds);
                    end.put("xAxis",da.getTimestamp());
                    end.put("itemStyle",ds);
                    list1.add(start);
                    list1.add(end);
                    list_smoke.add(list1);
                }


                long count = 0;
                for(int i=0;i<list.size();i++){


                    long endt;
                    if(i==(list.size()-1)){
                        endt = curtime;
                    }else{
                        if(list.get(i).getTimestamp()== list.get(i+1).getTimestamp()){
                            count+=list.get(i).getScore();
                            continue;
                        }
                        endt = list.get(i+1).getTimestamp();
                    }

                    List<ParameterMap> list1 = new ArrayList<>();
                    count+=list.get(i).getScore();
                    ParameterMap start = new ParameterMap();
                    ParameterMap end = new ParameterMap();
                    ParameterMap ds = new ParameterMap();
                    List<Object> lista = new ArrayList<>();
                    EventBean eventBean = list.get(i);
                    if(count/1000>0){
                        lista.add(eventBean.getTimestamp());
                        lista.add(4);
                        ds.put("color",color_fault);
                    }else if(count/100>0){
                        lista.add(eventBean.getTimestamp());
                        lista.add(3);
                        ds.put("color",color_alert);
                    }else if(count/10>0){
                        lista.add(eventBean.getTimestamp());
                        lista.add(2);
                        ds.put("color",color_dismantle);
                    }else if(count>0){
                        lista.add(eventBean.getTimestamp());
                        lista.add(1);
                        ds.put("color",color_low_battery);
                    }else {
                        lista.add(eventBean.getTimestamp());
                        lista.add(0);
                        ds.put("color",color_normal);
                    }
                    start.put("xAxis",eventBean.getTimestamp());
                    start.put("itemStyle",ds);
                    end.put("xAxis",endt);
                    end.put("itemStyle",ds);
                    list1.add(start);
                    list1.add(end);
                    list_smoke.add(list1);


                    list_smoke_state.add(lista);
                }


                List<Object> listt = new ArrayList<>();
                listt.add(curtime);
                if(count/1000>0){
                    listt.add(4);
                }else if(count/100>0){
                    listt.add(3);
                }else if(count/10>0){
                    listt.add(2);
                }else if(count>0){
                    listt.add(1);
                }else {
                    listt.add(0);
                }
                list_smoke_state.add(listt);

            }
        }


        ParameterMap pa = new ParameterMap();
        pa.put("platform",deviceBean.getPlatform());
        pa.put("productKey",deviceBean.getProdKey());
        pa.put("smoke_state",list_smoke_state);
        pa.put("smoke_state_mark",list_smoke);

        if(Const.PROFILE_PRODUCT_ID.equals(deviceBean.getProdKey())){
            List<ProfileLog> profileLogList = iProfileLogService.getSmokeStatusList(deviceId,histime,curtime);
            List<List<Object>> listsmoke_value = new ArrayList<>();
            List<List<Object>> listbattery_value = new ArrayList<>();
            for (ProfileLog profileLog:profileLogList) {
                long value_smoke = profileLog.getAlarmLevel();
                long value_bat = profileLog.getBattery_Level();
                long timestamp = profileLog.getTimestamp();
                List<Object> lista = new ArrayList<>();
                lista.add(timestamp);
                lista.add(value_bat);
                listbattery_value.add(lista);

                List<Object> listb = new ArrayList<>();
                listb.add(timestamp);
                listb.add(value_smoke);
                listsmoke_value.add(listb);
                pa.put("smoke_value",listsmoke_value);
                pa.put("battery_value",listbattery_value);
            }
        }
        else if(Const.ONENET_PRODUCT_ID.equals(deviceBean.getProdKey())){
            List<OnetEvent> onetEventList = iDevOneNetLogService.getSmokeStatusList(deviceId,histime,curtime);
            List<List<Object>> listsmoke_value = new ArrayList<>();
            List<List<Object>> listbattery_value = new ArrayList<>();
            for (OnetEvent onetEvent:onetEventList) {
                OnenetTransResultBean onenetTransResultBean = onetEvent.transToBean(onetEvent.getEventContent());
                long value_smoke = 0;
                long value_bat = 0;
                if(onenetTransResultBean.getEventType()==1){
                    value_smoke =  onenetTransResultBean.getDataBean().getSmoke_value();
                    value_bat = onenetTransResultBean.getDataBean().getBattery_value();
                }

                long timestamp = onetEvent.getCreateTime();
                List<Object> lista = new ArrayList<>();
                lista.add(timestamp);
                lista.add(value_bat);
                listbattery_value.add(lista);

                List<Object> listb = new ArrayList<>();
                listb.add(timestamp);
                listb.add(value_smoke);
                listsmoke_value.add(listb);
                pa.put("smoke_value",listsmoke_value);
                pa.put("battery_value",listbattery_value);
            }
        }else{
            List<List<Object>> listsmoke_value = iDevHistoryService.getSmokeValueList(deviceId,histime,curtime);
            List<List<Object>> listbattery_value = iDevHistoryService.getBatteryValueList(deviceId,histime,curtime);
            pa.put("smoke_value",listsmoke_value);
            pa.put("battery_value",listbattery_value);
        }

        return ResponseModel.getModel(ResultEnum.SUCCESS,pa);
    }


    /**
     * 按起止时间查询设备事件原始数据
     * @return
     */
    @RequestMapping(value="/queryDeviceEventData",method= RequestMethod.GET)
    @ResponseBody
    public Object queryDeviceEventData(){


        String deviceId = this.getParameterMap().getString("deviceId");
        String start_time = this.getParameterMap().getString("start_time");
        String end_time = this.getParameterMap().getString("end_time");

        if(StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(start_time) || StringUtils.isEmpty(end_time)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        if(!Tools.isLongNumber(start_time) || !Tools.isLongNumber(end_time)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_FORMAT_ERROR,null);
        }
        Device device = iDeviceService.getDeviceInfo(deviceId);
        if(device==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }


        long start_time_long = Long.parseLong(start_time);
        long end_time_long = Long.parseLong(end_time);

        ParameterMap map = new ParameterMap();
        map.put("device_name",device.getDeviceName());

        map.put("is_aep_product",!Const.ONENET_PRODUCT_ID.equals(device.getProdKey()));

        if(!Const.ONENET_PRODUCT_ID.equals(device.getProdKey())){
            map.put("event_list",iDeviceJsonService.getEventDataAtTime(deviceId,start_time_long,end_time_long));
        }else{
            List<OnetEvent> onetEventList = iDevOneNetLogService.getSmokeAllDataList(deviceId,start_time_long,end_time_long);
            List<ParameterMap> list = new ArrayList<>();
           for(OnetEvent event:onetEventList){
               OnenetTransResultBean onenetTransResultBean =  event.transToBean(event.getEventContent());
               ParameterMap p = new ParameterMap();
               p.put("eventType",onenetTransResultBean.getEventType());
               p.put("eventContent",event.getEventContent());
               p.put("createTime",event.getCreateTime());
               list.add(p);
           }
            map.put("event_list",list);
        }

        return ResponseModel.getModel(ResultEnum.SUCCESS,map);
    }

    /**
     * 按起止时间查询设备状态原始数据
     * @return
     */
    @RequestMapping(value="/queryDeviceStatusData",method= RequestMethod.GET)
    @ResponseBody
    public Object queryDeviceStatusData(){

        String deviceId = this.getParameterMap().getString("deviceId");
        String start_time = this.getParameterMap().getString("start_time");
        String end_time = this.getParameterMap().getString("end_time");

        if(StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(start_time) || StringUtils.isEmpty(end_time)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        if(!Tools.isLongNumber(start_time) || !Tools.isLongNumber(end_time)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_FORMAT_ERROR,null);
        }

        Device deviceBean = iDeviceService.getDeviceInfo(deviceId);
        if(deviceBean==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }

        long start_time_long = Long.parseLong(start_time);
        long end_time_long = Long.parseLong(end_time);

        List<StatusBean> list = iDeviceJsonService.getStatusDataAtTime(deviceId,start_time_long,end_time_long);


        return ResponseModel.getModel(ResultEnum.SUCCESS,list);
    }


    /**
     * 获取设备登录日志以及处理日志
     * @return
     */
    @RequestMapping(value="/queryDeviceLoginErrorHistory",method= RequestMethod.GET)
    @ResponseBody
    public Object queryDeviceLoginErrorHistory(){

        String device_id = this.getParameterMap().getString("deviceId");

        if(StringUtils.isEmpty(device_id)) return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);

        Device deviceBean = iDeviceService.getDeviceInfo(device_id);
        if(deviceBean==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }

        ParameterMap parameterMap = new ParameterMap();
        if(Const.ONENET_PRODUCT_ID.equals(deviceBean.getProdKey())){
            List<List<Object>> lists = iDevOneNetLogService.getLoginErrList(device_id);
            parameterMap.put("error_state",lists);
        }else if(Const.PROFILE_PRODUCT_ID.equals(deviceBean.getProdKey())){
            List<List<Object>> lists = iProfileLogService.getLoginErrList(device_id);
            parameterMap.put("error_state",lists);
        }else{
            List<List<Object>> lists = iDevHistoryService.getLoginErrList(device_id);
            parameterMap.put("error_state",lists);
        }


        return ResponseModel.getModel(ResultEnum.SUCCESS,parameterMap);
    }



    @RequestMapping(value="/deltWithLoginErr",method= RequestMethod.POST)
    @ResponseBody
    public Object deltWithLoginErr(){

        String device_id = this.getParameterMap().getString("deviceId");

        if(StringUtils.isEmpty(device_id)) return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);

        Device deviceBean = iDeviceService.getDeviceInfo(device_id);
        if(deviceBean==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }

        ParameterMap parameterMap = null;
        if(Const.ONENET_PRODUCT_ID.equals(deviceBean.getProdKey())){
            parameterMap = iDevOneNetLogService.isMultiLoginError(device_id);
        }else if(Const.PRODUCT_ID.equals(deviceBean.getProdKey())){
            parameterMap = iDevLogService.isMultiLoginError(device_id);
        }else {
            parameterMap = iProfileLogService.isMultiLoginError(device_id);
        }

        long value = Long.parseLong(parameterMap.getString("value"));
        if(value== 0){
            return ResponseModel.getModel(ResultEnum.IS_NO_LOGIN_ERROR,null);
        }

        String token = this.getRequest().getHeader("token");
        User userinfo = iUserApiService.getUserInfoByToken(token);
        return iDevHistoryService.handleLoginErr(device_id,userinfo.getUser_id());
    }


    @RequestMapping(value="/deepAnalysis",method= RequestMethod.GET)
    @ResponseBody
    public Object deepAnalysis(){

        String deviceId = this.getParameterMap().getString("deviceId");

        String start_time = this.getParameterMap().getString("start_time");

        String end_time = this.getParameterMap().getString("end_time");


        if(StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(start_time) || StringUtils.isEmpty(end_time)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        if(!Tools.isLongNumber(start_time) || !Tools.isLongNumber(end_time)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_FORMAT_ERROR,null);
        }


        Device device = iDeviceService.getDeviceInfo(deviceId);
        if(device==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }
        long start_time_long = Long.parseLong(start_time);
        long end_time_long = Long.parseLong(end_time);

        List<List<Object>> listsmoke = new ArrayList<>();
        List<List<Object>> listfault = new ArrayList<>();
        List<List<Object>> listdismantle = new ArrayList<>();
        List<List<Object>> listlowbattery = new ArrayList<>();
        List<List<Object>> listheart = new ArrayList<>();
        List<List<Object>> listsmokevalue = new ArrayList<>();
        List<List<Object>> listbattery_value = new ArrayList<>();
        List<List<Object>> listsnr = new ArrayList<>();
        List<List<Object>> listrsrp = new ArrayList<>();
        List<List<Object>> listtemp = new ArrayList<>();
        List<List<Object>> listcsq = new ArrayList<>();

        List<List<Object>> listecl = new ArrayList<>();
        List<List<Object>> listpci = new ArrayList<>();
        List<List<Object>> listrsrq = new ArrayList<>();
        List<List<Object>> listearfcn = new ArrayList<>();
        List<List<Object>> listtac = new ArrayList<>();
        StaticBean staticsmokevalue =new StaticBean();
        StaticBean staticbattery_value = new StaticBean();
        StaticBean staticsnr = new StaticBean();
        StaticBean staticrsrp= new StaticBean();
        StaticBean staticecl = new StaticBean();
        StaticBean statictemp= new StaticBean();
        StaticBean staticcsq = new StaticBean();
        StaticBean staticpci = new StaticBean();
        StaticBean staticrsrq= new StaticBean();
        StaticBean staticearfcn= new StaticBean();
        StaticBean statictac =new StaticBean();

        if(Const.PRODUCT_ID.equals(device.getProdKey())){
            listsmoke = iDevHistoryDeepService.smokeStateHistoryList(deviceId,start_time_long,end_time_long);
            listfault = iDevHistoryDeepService.faultHistoryList(deviceId,start_time_long,end_time_long);
            listdismantle = iDevHistoryDeepService.dismantleHistoryList(deviceId,start_time_long,end_time_long);
            listlowbattery = iDevHistoryDeepService.lowVoltHistoryList(deviceId,start_time_long,end_time_long);
            listheart = iDevHistoryDeepService.heartHistoryList(deviceId,start_time_long,end_time_long);
            staticsmokevalue = iDevHistoryDeepService.smokeLevelStatic(deviceId,start_time_long,end_time_long);
            staticbattery_value = iDevHistoryDeepService.batteryLevelStatic(deviceId,start_time_long,end_time_long);
            staticsnr = iDevHistoryDeepService.snrStatic(deviceId,start_time_long,end_time_long);
            staticrsrp = iDevHistoryDeepService.rsrpStatic(deviceId,start_time_long,end_time_long);
            staticecl = iDevHistoryDeepService.eclStatic(deviceId,start_time_long,end_time_long);
        }
        else if(Const.PROFILE_PRODUCT_ID.equals(device.getProdKey())){
            List<ProfileLog> profileLogList = iProfileLogService.getSmokeStatusList(deviceId,start_time_long,end_time_long);

            for(int i=0;i<profileLogList.size();i++){
                ProfileLog profileLog = profileLogList.get(i);
                List<Object> listStatus = new ArrayList<>();
                listStatus.add(profileLog.getTimestamp());
                listStatus.add(profileLog.getAlarm_Status());
                    switch ((int)profileLog.getAlarm_Status()){
                        case 1:
                        case 14:
                        case 15:
                            listsmoke.add(listStatus);
                            break;
                        case 3:
                        case 5:
                        case 6:
                            listfault.add(listStatus);
                            break;
                        case 10:
                            listdismantle.add(listStatus);
                            break;
                        case 4:
                            listlowbattery.add(listStatus);
                            break;
                    }


                    List<Object> listhearta = new ArrayList<>();
                    listhearta.add(profileLog.getTimestamp());
                    listhearta.add(1);
                    listheart.add(listhearta);

                    List<Object> listsmokevaluea = new ArrayList<>();
                    listsmokevaluea.add(profileLog.getTimestamp());
                    listsmokevaluea.add(profileLog.getAlarmLevel());
                    listsmokevalue.add(listsmokevaluea);

                    List<Object> listbattery_valuea = new ArrayList<>();
                    listbattery_valuea.add(profileLog.getTimestamp());
                    listbattery_valuea.add(profileLog.getBattery_Level());
                    listbattery_value.add(listbattery_valuea);

                    List<Object> listsnra = new ArrayList<>();
                    listsnra.add(profileLog.getTimestamp());
                    listsnra.add(profileLog.getSNR());
                    listsnr.add(listsnra);

                    List<Object> listrsrpa = new ArrayList<>();
                    listrsrpa.add(profileLog.getTimestamp());
                    listrsrpa.add(profileLog.getRSRP());
                    listrsrp.add(listrsrpa);


                    List<Object> listtempa = new ArrayList<>();
                    listtempa.add(profileLog.getTimestamp());
                    listtempa.add(profileLog.getTData());
                    listtemp.add(listtempa);

                    List<Object> listcsqa = new ArrayList<>();
                    listcsqa.add(profileLog.getTimestamp());
                    listcsqa.add(profileLog.getCSQ());
                    listcsq.add(listcsqa);

            }
            staticsmokevalue = iProfileLogService.getSmokeValueStatic(deviceId,start_time_long,end_time_long);
            staticbattery_value = iProfileLogService.getBatteryValueStatic(deviceId,start_time_long,end_time_long);
            staticsnr = iProfileLogService.getSnrStatic(deviceId,start_time_long,end_time_long);
            staticrsrp = iProfileLogService.getRsrpStatic(deviceId,start_time_long,end_time_long);
            statictemp = iProfileLogService.getTempStatic(deviceId,start_time_long,end_time_long);
            staticcsq = iProfileLogService.getCsqStatic(deviceId,start_time_long,end_time_long);
            staticsmokevalue.setHistoryList(listsmokevalue);
            staticbattery_value.setHistoryList(listbattery_value);
            staticsnr.setHistoryList(listsnr);
            staticrsrp.setHistoryList(listrsrp);
            statictemp.setHistoryList(listtemp);
            staticcsq.setHistoryList(listcsq);
        } else {
            List<OnetEvent> onetEventList = iDevOneNetLogService.getSmokeStatusList(deviceId,start_time_long,end_time_long);
            double maxsmokevalue=0,minsmokevalue=0,sumsmokevalue=0,
                    maxbatteryvalue=0,minbatteryvalue=0,sumbatteryvalue=0,
                    maxsnr=0,minsnr=0,sumsnr=0,
                    maxrsrp=0,minrsrp=0,sumrsrp=0,
                    maxecl=0,minecl=0,sumecl=0,
                    maxtemp=0,mintemp=0,sumtemp=0,
                    maxcsq=0,mincsq=0,sumcsq=0,
                    maxpci=0,minpci=0,sumpci=0,
                    maxrsrq=0,minrsrq=0,sumrsrq=0,
                    maxearfcn=0,minearfcn=0,sumearfcn=0,
                    maxtac=0,mintac=0,sumtac=0;
            long count=0;
            for(int i=0;i<onetEventList.size();i++){
                OnetEvent event = onetEventList.get(i);
                OnenetTransResultBean op = event.transToBean(event.getEventContent());
                if(op.getEventType()==1){
                    count++;
                    if(count==1){
                        maxsmokevalue = op.getDataBean().getSmoke_value();
                        minsmokevalue = op.getDataBean().getSmoke_value();
                        maxbatteryvalue = op.getDataBean().getBattery_value();
                        minbatteryvalue = op.getDataBean().getBattery_value();
                        maxsnr = op.getDataBean().getSnr();
                        minsnr = op.getDataBean().getSnr();
                        maxrsrp = op.getDataBean().getRsrp();
                        minrsrp = op.getDataBean().getRsrp();
                        maxecl = op.getDataBean().getEcl();
                        minecl = op.getDataBean().getEcl();
                        maxtemp = op.getDataBean().getTemperature();
                        mintemp = op.getDataBean().getTemperature();
                        maxcsq = op.getDataBean().getCsq();
                        mincsq = op.getDataBean().getCsq();
                        maxpci = op.getDataBean().getPci();
                        minpci = op.getDataBean().getPci();
                        maxrsrq = op.getDataBean().getRsrq();
                        minrsrq = op.getDataBean().getRsrq();
                        maxearfcn = op.getDataBean().getEarfcn();
                        minearfcn = op.getDataBean().getEarfcn();
                        maxtac = op.getDataBean().getTac();
                        mintac = op.getDataBean().getTac();
                    }
                    List<Object> listStatus = new ArrayList<>();
                    listStatus.add(event.getCreateTime());
                    listStatus.add(op.getDataBean().getDevice_status());
                    switch ((int)op.getDataBean().getDevice_status()){
                        case 1:
                        case 14:
                        case 15:
                            listsmoke.add(listStatus);
                            break;
                        case 3:
                        case 5:
                        case 6:
                            listfault.add(listStatus);
                            break;
                        case 10:
                            listdismantle.add(listStatus);
                            break;
                        case 4:
                            listlowbattery.add(listStatus);
                            break;
                    }

                    List<Object> listhearta = new ArrayList<>();
                    listhearta.add(event.getCreateTime());
                    listhearta.add(1);
                    listheart.add(listhearta);

                    List<Object> listsmokevaluea = new ArrayList<>();
                    listsmokevaluea.add(event.getCreateTime());
                    listsmokevaluea.add(op.getDataBean().getSmoke_value());
                    listsmokevalue.add(listsmokevaluea);
                    sumsmokevalue+=op.getDataBean().getSmoke_value();
                    if(op.getDataBean().getSmoke_value()<minsmokevalue){
                        minsmokevalue = op.getDataBean().getSmoke_value();
                    }
                    if(op.getDataBean().getSmoke_value()>maxsmokevalue){
                        maxsmokevalue = op.getDataBean().getSmoke_value();
                    }

                    List<Object> listbattery_valuea = new ArrayList<>();
                    listbattery_valuea.add(event.getCreateTime());
                    listbattery_valuea.add(op.getDataBean().getBattery_value());
                    listbattery_value.add(listbattery_valuea);
                    sumbatteryvalue+=op.getDataBean().getBattery_value();
                    if(op.getDataBean().getBattery_value()<minbatteryvalue){
                        minbatteryvalue = op.getDataBean().getBattery_value();
                    }
                    if(op.getDataBean().getBattery_value()>maxbatteryvalue){
                        maxbatteryvalue = op.getDataBean().getBattery_value();
                    }


                    List<Object> listsnra = new ArrayList<>();
                    listsnra.add(event.getCreateTime());
                    listsnra.add(op.getDataBean().getSnr());
                    listsnr.add(listsnra);
                    sumsnr+=op.getDataBean().getSnr();
                    if(op.getDataBean().getSnr()<minsnr){
                        minsnr = op.getDataBean().getSnr();
                    }
                    if(op.getDataBean().getSnr()>maxsnr){
                        maxsnr = op.getDataBean().getSnr();
                    }

                    List<Object> listrsrpa = new ArrayList<>();
                    listrsrpa.add(event.getCreateTime());
                    listrsrpa.add(op.getDataBean().getRsrp());
                    listrsrp.add(listrsrpa);
                    sumrsrp+=op.getDataBean().getRsrp();
                    if(op.getDataBean().getRsrp()<minrsrp){
                        minrsrp = op.getDataBean().getRsrp();
                    }
                    if(op.getDataBean().getRsrp()>maxrsrp){
                        maxrsrp = op.getDataBean().getRsrp();
                    }

                    List<Object> listecla = new ArrayList<>();
                    listecla.add(event.getCreateTime());
                    listecla.add(op.getDataBean().getEcl());
                    listecl.add(listecla);
                    sumecl+=op.getDataBean().getEcl();
                    if(op.getDataBean().getEcl()<minecl){
                        minecl = op.getDataBean().getEcl();
                    }
                    if(op.getDataBean().getEcl()>maxecl){
                        maxecl = op.getDataBean().getEcl();
                    }

                    List<Object> listtempa = new ArrayList<>();
                    listtempa.add(event.getCreateTime());
                    listtempa.add(op.getDataBean().getTemperature());
                    listtemp.add(listtempa);
                    sumtemp+=op.getDataBean().getTemperature();
                    if(op.getDataBean().getTemperature()<mintemp){
                        mintemp = op.getDataBean().getTemperature();
                    }
                    if(op.getDataBean().getTemperature()>maxtemp){
                        maxtemp = op.getDataBean().getTemperature();
                    }

                    List<Object> listcsqa = new ArrayList<>();
                    listcsqa.add(event.getCreateTime());
                    listcsqa.add(op.getDataBean().getCsq());
                    listcsq.add(listcsqa);
                    sumcsq+=op.getDataBean().getCsq();
                    if(op.getDataBean().getCsq()<mincsq){
                        mincsq = op.getDataBean().getCsq();
                    }
                    if(op.getDataBean().getCsq()>maxcsq){
                        maxcsq = op.getDataBean().getCsq();
                    }

                    List<Object> listpcia = new ArrayList<>();
                    listpcia.add(event.getCreateTime());
                    listpcia.add(op.getDataBean().getPci());
                    listpci.add(listpcia);
                    sumpci+=op.getDataBean().getPci();
                    if(op.getDataBean().getPci()<minpci){
                        minpci = op.getDataBean().getPci();
                    }
                    if(op.getDataBean().getPci()>maxpci){
                        maxpci = op.getDataBean().getPci();
                    }

                    List<Object> listrsrqa = new ArrayList<>();
                    listrsrqa.add(event.getCreateTime());
                    listrsrqa.add(op.getDataBean().getRsrq());
                    listrsrq.add(listrsrqa);
                    sumrsrq+=op.getDataBean().getRsrq();
                    if(op.getDataBean().getRsrq()<minrsrq){
                        minrsrq = op.getDataBean().getRsrq();
                    }
                    if(op.getDataBean().getRsrq()>maxrsrq){
                        maxrsrq = op.getDataBean().getRsrq();
                    }

                    List<Object> listearfcna = new ArrayList<>();
                    listearfcna.add(event.getCreateTime());
                    listearfcna.add(op.getDataBean().getEarfcn());
                    listearfcn.add(listearfcna);
                    sumearfcn+=op.getDataBean().getEarfcn();
                    if(op.getDataBean().getEarfcn()<minearfcn){
                        minearfcn = op.getDataBean().getEarfcn();
                    }
                    if(op.getDataBean().getEarfcn()>maxearfcn){
                        maxearfcn = op.getDataBean().getEarfcn();
                    }

                    List<Object> listtaca = new ArrayList<>();
                    listtaca.add(event.getCreateTime());
                    listtaca.add(op.getDataBean().getTac());
                    listtac.add(listtaca);
                    sumtac+=op.getDataBean().getTac();
                    if(op.getDataBean().getTac()<mintac){
                        mintac = op.getDataBean().getTac();
                    }
                    if(op.getDataBean().getTac()>maxtac){
                        maxtac = op.getDataBean().getTac();
                    }
                }
            }

            if(count>0){
                staticsmokevalue.setMax(DataUtils.getDoubleString(maxsmokevalue));
                staticsmokevalue.setMin(DataUtils.getDoubleString(minsmokevalue));
                staticsmokevalue.setAvg(String.format("%.2f", (sumsmokevalue)/count));
            }else{
                staticsmokevalue.setMax("").setMin("").setAvg("");
            }
            staticsmokevalue.setHistoryList(listsmokevalue);

            if(count>0){
                staticbattery_value.setMax(DataUtils.getDoubleString(maxbatteryvalue));
                staticbattery_value.setMin(DataUtils.getDoubleString(minbatteryvalue));
                staticbattery_value.setAvg(String.format("%.2f", (sumbatteryvalue)/count));
            }else{
                staticbattery_value.setMax("").setMin("").setAvg("");
            }
            staticbattery_value.setHistoryList(listbattery_value);


            if(count>0){
                staticsnr.setMax(DataUtils.getDoubleString(maxsnr));
                staticsnr.setMin(DataUtils.getDoubleString(minsnr));
                staticsnr.setAvg(String.format("%.2f", (sumsnr)/count));
            }else{
                staticsnr.setMax("").setMin("").setAvg("");
            }
            staticsnr.setHistoryList(listsnr);


            if(count>0){
                staticrsrp.setMax(DataUtils.getDoubleString(maxrsrp));
                staticrsrp.setMin(DataUtils.getDoubleString(minrsrp));
                staticrsrp.setAvg(String.format("%.2f", (sumrsrp)/count));
            }else{
                staticrsrp.setMax("").setMin("").setAvg("");
            }
            staticrsrp.setHistoryList(listrsrp);

            if(count>0){
                staticecl.setMax(DataUtils.getDoubleString(maxecl));
                staticecl.setMin(DataUtils.getDoubleString(minecl));
                staticecl.setAvg(String.format("%.2f", (sumecl)/count));
            }else{
                staticecl.setMax("").setMin("").setAvg("");
            }
            staticecl.setHistoryList(listecl);

            if(count>0){
                statictemp.setMax(DataUtils.getDoubleString(maxtemp));
                statictemp.setMin(DataUtils.getDoubleString(mintemp));
                statictemp.setAvg(String.format("%.2f", (sumtemp)/count));
            }else{
                statictemp.setMax("").setMin("").setAvg("");
            }
            statictemp.setHistoryList(listtemp);


            if(count>0){
                staticcsq.setMax(DataUtils.getDoubleString(maxcsq));
                staticcsq.setMin(DataUtils.getDoubleString(mincsq));
                staticcsq.setAvg(String.format("%.2f", (sumcsq)/count));
            }else{
                staticcsq.setMax("").setMin("").setAvg("");
            }
            staticcsq.setHistoryList(listcsq);

            if(count>0){
                staticpci.setMax(DataUtils.getDoubleString(maxpci));
                staticpci.setMin(DataUtils.getDoubleString(minpci));
                staticpci.setAvg(String.format("%.2f", (sumpci)/count));
            }else{
                staticpci.setMax("").setMin("").setAvg("");
            }
            staticpci.setHistoryList(listpci);

            if(count>0){
                staticrsrq.setMax(DataUtils.getDoubleString(maxrsrq));
                staticrsrq.setMin(DataUtils.getDoubleString(minrsrq));
                staticrsrq.setAvg(String.format("%.2f", (sumrsrq)/count));
            }else{
                staticrsrq.setMax("").setMin("").setAvg("");
            }
            staticrsrq.setHistoryList(listrsrq);

            if(count>0){
                staticearfcn.setMax(DataUtils.getDoubleString(maxearfcn));
                staticearfcn.setMin(DataUtils.getDoubleString(minearfcn));
                staticearfcn.setAvg(String.format("%.2f", (sumearfcn)/count));
            }else{
                staticearfcn.setMax("").setMin("").setAvg("");
            }
            staticearfcn.setHistoryList(listearfcn);

            if(count>0){
                statictac.setMax(DataUtils.getDoubleString(maxtac));
                statictac.setMin(DataUtils.getDoubleString(mintac));
                statictac.setAvg(String.format("%.2f", (sumtac)/count));
            }else{
                statictac.setMax("").setMin("").setAvg("");
            }
            statictac.setHistoryList(listtac);
        }




        ParameterMap m = new ParameterMap();
        m.put("smoke_state",listsmoke);
        m.put("fault_state",listfault);
        m.put("dismantle_state",listdismantle);
        m.put("lowbattery_state",listlowbattery);
        ParameterMap parameterMap = new ParameterMap();
        parameterMap.put("device_state",m);
        parameterMap.put("heartbeat",listheart);
        parameterMap.put("smoke_value",staticsmokevalue);
        parameterMap.put("battery_value",staticbattery_value);
        parameterMap.put("snr",staticsnr);
        parameterMap.put("rsrp",staticrsrp);
        parameterMap.put("ecl",staticecl);

        if(Const.PRODUCT_ID.equals(device.getProdKey())){
            StaticBean staticbattery_voltage = iDevHistoryDeepService.batteryVoltageStatic(deviceId,start_time_long,end_time_long);
            StaticBean staticsingalPower = iDevHistoryDeepService.signalPowerStatic(deviceId,start_time_long,end_time_long);
            StaticBean statictxPower = iDevHistoryDeepService.txPowerStatic(deviceId,start_time_long,end_time_long);
            StaticBean staticsinr = iDevHistoryDeepService.sinrStatic(deviceId,start_time_long,end_time_long);
            parameterMap.put("battery_voltage",staticbattery_voltage);
            parameterMap.put("signal_power",staticsingalPower);
            parameterMap.put("tx_power",statictxPower);
            parameterMap.put("sinr",staticsinr);
        }
        else {
            parameterMap.put("temperature",statictemp);
            parameterMap.put("csq",staticcsq);
            parameterMap.put("pci",staticpci);
            parameterMap.put("rsrq",staticrsrq);
            parameterMap.put("earfcn",staticearfcn);
            parameterMap.put("tac",statictac);
        }



        return ResponseModel.getModel(ResultEnum.SUCCESS,parameterMap);
    }

    @RequestMapping(value="/statics",method= RequestMethod.GET)
    @ResponseBody
    public Object statics(){
        List<Device>  deviceList = iDeviceService.getAllDeviceList();
        List<ParameterMap>  list = new ArrayList<>();
        List<ParameterMap> list_dismantle = new ArrayList<>();
        List<ParameterMap> list_alarm = new ArrayList<>();
        List<ParameterMap> list_fault = new ArrayList<>();
        List<ParameterMap> list_lowvolt = new ArrayList<>();
        List<ParameterMap> list_other = new ArrayList<>();
        int count_normal = 0;
        int count_low_volt = 0;
        int count_dismantle = 0;
        int count_smoke_alarm = 0;
        int count_fault = 0;
        int count_other = 0;
        for (int i=0;i<deviceList.size();i++){
            Device device = deviceList.get(i);
            if(Const.PRODUCT_ID.equals(device.getProdKey())){
                long count_total = 0;
                ParameterMap status_fault = iDevLogService.SensorFault(device.getDeviceId());
                long value_fault = Long.parseLong(status_fault.getString("value"));
                count_total+=(value_fault==1?1000:0);
                ParameterMap status_smoke = iDevLogService.SmokeAlarmStatus(device.getDeviceId());
                long value_smoke = Long.parseLong(status_smoke.getString("value"));
                count_total+=(value_smoke==1?100:0);
                ParameterMap status_dismantle = iDevLogService.DismantleStatus(device.getDeviceId());
                long value_dismantle = Long.parseLong(status_dismantle.getString("value"));
                count_total+=(value_dismantle==1?10:0);
                ParameterMap status_lowvolt = iDevLogService.LowVoltFault(device.getDeviceId());
                long value_lowvolt = Long.parseLong(status_lowvolt.getString("value"));
                count_total+=(value_lowvolt==1?1:0);

                if(count_total/1000>0){
                    count_fault++;
                    ParameterMap parameterMap = new ParameterMap();
                    parameterMap.put("deviceId",device.getDeviceId());
                    parameterMap.put("deviceName",device.getDeviceName());
                    parameterMap.put("prodKey",device.getProdKey());
                    list_fault.add(parameterMap);
                }else if(count_total/100>0){
                    count_smoke_alarm++;
                    ParameterMap parameterMap = new ParameterMap();
                    parameterMap.put("deviceId",device.getDeviceId());
                    parameterMap.put("deviceName",device.getDeviceName());
                    parameterMap.put("prodKey",device.getProdKey());
                    list_alarm.add(parameterMap);
                }else if(count_total/10>0){
                    count_dismantle++;
                    ParameterMap parameterMap = new ParameterMap();
                    parameterMap.put("deviceId",device.getDeviceId());
                    parameterMap.put("deviceName",device.getDeviceName());
                    parameterMap.put("prodKey",device.getProdKey());
                    list_dismantle.add(parameterMap);
                }else if(count_total>0){
                    count_low_volt++;
                    ParameterMap parameterMap = new ParameterMap();
                    parameterMap.put("deviceId",device.getDeviceId());
                    parameterMap.put("deviceName",device.getDeviceName());
                    parameterMap.put("prodKey",device.getProdKey());
                    list_lowvolt.add(parameterMap);
                }else{
                    count_normal++;
                }
            }else if(Const.PROFILE_PRODUCT_ID.equals(device.getProdKey())){
                ParameterMap parameterMap = new ParameterMap();
                parameterMap.put("deviceId",device.getDeviceId());
                parameterMap.put("deviceName",device.getDeviceName());
                parameterMap.put("prodKey",device.getProdKey());
                ProfileLog profileLog = iProfileLogService.ShadowStatus(device.getDeviceId());
                if(profileLog==null){
                    count_normal++;
                }else{
                        switch ((int)profileLog.getAlarm_Status()){
                            case 1:
                                count_smoke_alarm++;
                                list_alarm.add(parameterMap);
                                break;
                            case 3:
                            case 5:
                                count_fault++;
                                list_fault.add(parameterMap);
                                break;
                            case 4:
                                count_low_volt++;
                                list_lowvolt.add(parameterMap);
                                break;
                            case 10:
                                count_dismantle++;
                                list_dismantle.add(parameterMap);
                                break;
                            case 7:
                                count_normal++;
                                break;
                            default:
                                count_other++;
                                list_other.add(parameterMap);
                                break;
                        }
                }
            }
            else if(Const.PROFILE_PRODUCT_ID_GC.equals(device.getProdKey()) || Const.PROFILE_PRODUCT_ID_GC_2.equals(device.getProdKey())){
                ProfileGCInfoBean profileGCInfoBean = iProfileGCService.ShadowStatus(device.getDeviceId());
                ParameterMap parameterMap = new ParameterMap();
                parameterMap.put("deviceId",device.getDeviceId());
                parameterMap.put("deviceName",device.getDeviceName());
                parameterMap.put("prodKey",device.getProdKey());
                if(profileGCInfoBean!=null){
                    profileGCInfoBean.transToBean();
                    if(profileGCInfoBean.getProtocol_Number()==1 && profileGCInfoBean.getUpdateBean1()!=null){
                        if(profileGCInfoBean.getUpdateBean1().isDismantle()){
                            count_dismantle++;
                            list_dismantle.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean1().isSensorFault()||profileGCInfoBean.getUpdateBean1().isSDComAbnormal()){
                            count_fault++;
                            list_fault.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean1().isSmokeAlarm()||profileGCInfoBean.getUpdateBean1().isLocalTestAlarm()){
                            count_smoke_alarm++;
                            list_alarm.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean1().isLowBattery()){
                            count_low_volt++;
                            list_lowvolt.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean1().isLocalTestAlarm()||profileGCInfoBean.getUpdateBean1().isLifeStop()
                                ||profileGCInfoBean.getUpdateBean1().isLowBNoDisturb()||profileGCInfoBean.getUpdateBean1().isSensorFaultNoDisturb()
                                ||profileGCInfoBean.getUpdateBean1().isSmokeSilence()){
                            count_other++;
                            list_other.add(parameterMap);
                        }else{
                            count_normal++;
                        }


                    }else if(profileGCInfoBean.getProtocol_Number()==2 && profileGCInfoBean.getUpdateBean2()!=null){
                        if(profileGCInfoBean.getUpdateBean2().isLocalTestAlarm()
                                ||profileGCInfoBean.getUpdateBean2().isRemoteTestAlarm()
                                ||profileGCInfoBean.getUpdateBean2().isGasAlarm()
                                ||profileGCInfoBean.getUpdateBean2().isCoAlarm()){
                            count_smoke_alarm++;
                            list_alarm.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean2().isLowBattery()){
                            count_low_volt++;
                            list_lowvolt.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean2().isGasSensorFault()||profileGCInfoBean.getUpdateBean2().isCoSensorFault()||profileGCInfoBean.getUpdateBean2().isSDComAbnormal()){
                            count_fault++;
                            list_fault.add(parameterMap);
                        }else if(profileGCInfoBean.getUpdateBean2().isLifeStop()||
                                profileGCInfoBean.getUpdateBean2().isCoSensorFaultNoDisturb()||
                                profileGCInfoBean.getUpdateBean2().isGasSensorFaultNoDisturb()||
                                profileGCInfoBean.getUpdateBean2().isGasSilence()||
                                profileGCInfoBean.getUpdateBean2().isCoSilence()||
                                profileGCInfoBean.getUpdateBean2().isLowBNoDisturb()){
                            count_other++;
                            list_other.add(parameterMap);
                        }else{
                            count_normal++;
                        }


                    }else if(profileGCInfoBean.getProtocol_Number()==3 && profileGCInfoBean.getUpdateBean3()!=null){
                        long status = profileGCInfoBean.getUpdateBean3().getDevice_status();
                        switch ((int)status){
                            case 1:
                            case 9:
                                count_smoke_alarm++;
                                list_alarm.add(parameterMap);
                                break;
                            case 3:
                            case 10:
                                count_fault++;
                                list_fault.add(parameterMap);
                                break;
                            case 2:
                            case 6:
                            case 8:
                                count_other++;
                                list_other.add(parameterMap);
                                break;
                            default:
                                if(status==7){
                                    count_normal++;
                                }else{
                                    count_other++;
                                    list_other.add(parameterMap);
                                }
                                break;
                        }

                    }else {
                        count_normal++;
                    }
                }else{
                    count_normal++;
                }
            }
            else{
                ParameterMap parameterMap = new ParameterMap();
                parameterMap.put("deviceId",device.getDeviceId());
                parameterMap.put("deviceName",device.getDeviceName());
                parameterMap.put("prodKey",device.getProdKey());
                OnetEvent onetEvent = iDevOneNetLogService.getSmokeStatus(device.getDeviceId());
                if(onetEvent==null){
                    count_normal++;
                }else{
                    OnenetTransResultBean onenetTransResultBean = onetEvent.transToBean(onetEvent.getEventContent());
                    if(onenetTransResultBean.getEventType()==1){
                        switch ((int)onenetTransResultBean.getDataBean().getDevice_status()){
                            case 1:
                                count_smoke_alarm++;
                                list_alarm.add(parameterMap);
                                break;
                            case 3:
                            case 5:
                                count_fault++;
                                list_fault.add(parameterMap);
                                break;
                            case 4:
                                count_low_volt++;
                                list_lowvolt.add(parameterMap);
                                break;
                            case 10:
                                count_dismantle++;
                                list_dismantle.add(parameterMap);
                                break;
                            case 7:
                                count_normal++;
                                break;
                            default:
                                count_other++;
                                list_other.add(parameterMap);
                                break;
                        }
                    }else{
                        count_other++;
                        list_other.add(parameterMap);
                    }
                }

            }
        }

        ParameterMap fault = new ParameterMap();
        fault.put("name","故障");
        fault.put("value",count_fault);
        ParameterMap smoke = new ParameterMap();
        smoke.put("name","火灾告警");
        smoke.put("value",count_smoke_alarm);
        ParameterMap dismantle = new ParameterMap();
        dismantle.put("name","拆除");
        dismantle.put("value",count_dismantle);
        ParameterMap lowvolt = new ParameterMap();
        lowvolt.put("name","低电压");
        lowvolt.put("value",count_low_volt);
        ParameterMap other = new ParameterMap();
        other.put("name","其他");
        other.put("value",count_other);
        ParameterMap normal = new ParameterMap();
        normal.put("name","正常");
        normal.put("value",count_normal);

        list.add(normal);
        list.add(fault);
        list.add(smoke);
        list.add(dismantle);
        list.add(lowvolt);
        list.add(other);

        List<ParameterMap> listnetstatus = iMainSurveyService.getNetStatusStatics();
        HashMap<String,Object> soft_hard = iMainSurveyService.getSoftHadWareStatics();

        ParameterMap parameterMap = new ParameterMap();
        parameterMap.put("device_status",list);
        parameterMap.put("net_status",listnetstatus);
        parameterMap.put("software_version",soft_hard.get("soft"));
        parameterMap.put("hardware_version",soft_hard.get("hard"));
        parameterMap.put("fault_list",list_fault);
        parameterMap.put("alarm_list",list_alarm);
        parameterMap.put("dismantle_list",list_dismantle);
        parameterMap.put("other_list",list_other);
        parameterMap.put("lowvolt_list",list_lowvolt);
        return ResponseModel.getModel(ResultEnum.SUCCESS,parameterMap);
    }

    @RequestMapping(value="/modifyHeartTime",method= RequestMethod.POST)
    @ResponseBody
    public Object modifyHeartTime(@RequestBody JSONObject jsonParam){

        long min  = jsonParam.getLongValue("min");
        String deviceId = jsonParam.getString("deviceId");
        if(StringUtils.isEmpty(deviceId)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        if(min<=0){
            return ResponseModel.getModel(ResultEnum.PARAMETER_VALUE_ERROR,null);
        }

        Device device = iDeviceService.getDeviceInfo(deviceId);
        if(device == null) {
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }

        return iDeviceService.modifyHeartTime(min,deviceId);
    }


    //近30天心跳包分析
    @RequestMapping(value="/heartAnalysis",method= RequestMethod.GET)
    @ResponseBody
    public Object heartAnalysis() {
        String deviceId = this.getParameterMap().getString("deviceId");


        if(Tools.isEmpty(deviceId)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        Calendar now = Calendar.getInstance();
        long curtime = now.getTime().getTime();
        now.add(Calendar.DAY_OF_MONTH, -30);
        long startTime = now.getTime().getTime();

        Device device = iDeviceService.getDeviceInfo(deviceId);

        if(Const.PRODUCT_ID.equals(device.getProdKey())){
          List<List<Object>>  listheart = iDevHistoryDeepService.heartHistoryList(deviceId,startTime,curtime);


            List<List<Object>> list_heart_area = new ArrayList<>();
            List<List<Object>> list_heart = new ArrayList<>();
          if(listheart.size()>1){
              List<Object> heartFirst = listheart.get(0);
              long init_he = (long)heartFirst.get(0);
              long count = (curtime - init_he)/(device.getHeartTime()*60000);
              for(int i=1;i<count;i++){

                  long bztime = init_he+device.getHeartTime()*60000*i;
                  long wucha =  device.getHeartTime()*6000;
                  long histimea = bztime - wucha;
                  long curtimea = bztime + wucha;


                  List<Object> l1 = new ArrayList<>();

                  l1.add(histimea);
                  l1.add(0);
                  list_heart.add(l1);

                  List<Object> l2 = new ArrayList<>();

                  l2.add(curtimea);
                  l2.add(0);
                  list_heart.add(l2);


                  List<Object> list1 = new ArrayList<>();
                  ParameterMap start = new ParameterMap();
                  ParameterMap end = new ParameterMap();
                  ParameterMap ds = new ParameterMap();
                  ds.put("color",color_theme);

                  start.put("xAxis",histimea);
                  start.put("itemStyle",ds);
                  end.put("xAxis",curtimea);
                  end.put("itemStyle",ds);
                  list1.add(start);
                  list1.add(end);
                  list_heart_area.add(list1);
              }

          }

          ParameterMap map = new ParameterMap();
          map.put("heart_theo",list_heart);
          map.put("heart_theo_area",list_heart_area);
          map.put("heart",listheart);
          return ResponseModel.getModel(ResultEnum.SUCCESS,map);
        }else{
            return ResponseModel.getModel(ResultEnum.HEART_ANALYSIS_IS_NOT_SUPPORT_FOR_THIS_PRODUCT,null);
        }

    }

    //获取导入设备详细报告
    @RequestMapping(value="/getReportDetail",method= RequestMethod.GET)
    @ResponseBody
    public Object getReportDetail() {

        String reportId = this.getParameterMap().getString("report_id");

        if(Tools.isEmpty(reportId)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        if(!Tools.isLongNumber(reportId)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_FORMAT_ERROR,null);
        }


        long reportid = Long.parseLong(reportId);

        ExcelReportBean excelReportBean = iExcelDeviceService.getReport(reportid);
        if(excelReportBean==null){
            ResponseModel.getModel(ResultEnum.EXCEL_REPORT_IS_NOT_EXIST,null);
        }

        List<ExcelResultBean> list = iExcelDeviceService.getReportList(reportid);


        return ResponseModel.getModel(ResultEnum.SUCCESS,list);
    }


    //获取导入设备详细报告
    @RequestMapping(value="/deleteDevice",method= RequestMethod.POST)
    @ResponseBody
    public Object deleteDevice(@RequestBody JSONObject jsonObject) {
        String deviceId = jsonObject.getString("deviceId");
        if(Tools.isEmpty(deviceId)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        Device device = iDeviceService.getDeviceInfo(deviceId);
        if(device==null){
            return ResponseModel.getModel(ResultEnum.DEVICE_NOT_EXIST_ERROR,null);
        }



        return iDeviceService.deleteDevice(device);
    }


    private void sortList(List<EventBean> list) {
        if (list.size() <= 1) {

        } else {
            for (int i = 0; i < list.size() - 1; i++) {
                for (int j = 0; j < list.size() - 1 - i; j++) {
                    if (list.get(j).getTimestamp() > list.get(j+1).getTimestamp()) {
                        EventBean statusBean1 = new EventBean();
                        statusBean1.setTimestamp(list.get(j).getTimestamp());
                        statusBean1.setScore(list.get(j).getScore());

                        EventBean statusBean2 = new EventBean();
                        statusBean2.setTimestamp(list.get(j+1).getTimestamp());
                        statusBean2.setScore(list.get(j+1).getScore());

                        list.set(j,statusBean2);
                        list.set(j+1,statusBean1);
                    }
                }
            }

        }
    }

}
